package com.qubuyer.core.framework

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.qubuyer.core.http.Api

/**
 * Author: linwg
 * Time: 2020/10/10 0010
 * Description:
 */
open class BaseModel : LifecycleEventObserver {

    private var mOwner: LifecycleOwner? = null

    fun init(owner: LifecycleOwner) {
        mOwner = owner
        owner.lifecycle.addObserver(this@BaseModel)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        if (mOwner?.lifecycle?.currentState == Lifecycle.State.DESTROYED) {
            mOwner?.lifecycle?.removeObserver(this)
            mOwner = null
        }
    }

    inline fun <reified T> injectApi(name: Class<T> = T::class.java): Lazy<T> {
        return lazy { Api.getInstance().create(name) }
    }
}